/* ****************************************************************************
ncom-mesh.cpp
-------------------------------------------------------------------------------

Copyright (c) 2017, Tain L.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

**************************************************************************** */

#include "../core/api-dev.h"
#include "ncom-mesh.h"

using namespace Spears;

#define NCOM_TYPE	"mesh-ncom"

NComMesh::NComMesh(const Asset::atMesh& mesh)
{
	load_asset(mesh);
}

NComMesh::~NComMesh()
{}

std::string NComMesh::type() const
{
	return NCOM_TYPE;
}

bool NComMesh::is_detectable() const
{
	return true;
}

void NComMesh::load_asset(const Asset::atMesh& mesh)
{
	m_vertices.clear();
	for (auto const& vtx : mesh.m_vertices)
	{
		Math::Point3 the_vtx(vtx.x, vtx.y, vtx.z);
		m_vertices.push_back(the_vtx);
	}

	m_normals.clear();
	for (auto const& nml : mesh.m_normals)
	{
		Math::Vector3 the_nml(nml.x, nml.y, nml.z);
		m_normals.push_back(the_nml);
	}

	m_faces.clear();
	for (auto const& face : mesh.m_faces)
	{
		Math::TriangleFace the_face(face.v1, face.v2, face.v3);
		m_faces.push_back(the_face);
	}
}

bool NComMesh::intersect(Math::Intersection& intersection, const Math::Ray3& ray)
{
	using Vector3 = Math::Vector3;
	using Point3 = Math::Point3;
	using decimal = Math::decimal;
	using TriFace = Math::TriangleFace;
	
	decimal travel = Math::infinity;
	bool	hit = false;

	for (auto& face : m_faces)
	{
		decimal		t, u, v;

		if (true == _ray_cross_triangle(ray,
			m_vertices[face.m_vertex_idx[0]],
			m_vertices[face.m_vertex_idx[1]],
			m_vertices[face.m_vertex_idx[2]],
			t, u, v))
		{
			if (t < travel &&
				t > 0.f)
			{
				hit = true;
				travel = t;

				intersection.m_ray_in = ray;
				intersection.m_hit_point = ray.on_ray(t);

				intersection.m_normal = m_normals[face.m_vertex_idx[0]];
				intersection.m_normal += m_normals[face.m_vertex_idx[1]];
				intersection.m_normal += m_normals[face.m_vertex_idx[2]];
				intersection.m_normal.normalize();

				intersection.m_travel = t;
			}
		}
	}

	return hit;
}

inline bool NComMesh::_ray_cross_triangle(const  Math::Ray3& ray,
	const  Math::Point3& v0, const  Math::Point3& v1, const  Math::Point3& v2,
	Math::decimal& travel, Math::decimal& u, Math::decimal& v) const
{
	using Vector3 = Math::Vector3;
	using decimal = Math::decimal;

	Vector3 E1(v1);
	E1 -= v0;

	Vector3 E2(v2);
	E2 -= v0;

	Vector3 P(ray.m_direction);
	P.cross(E2);

	// determinant
	float det = E1.dot(P);

	// keep det > 0, modify T accordingly
	Vector3 T;
	if (det > 0)
	{
		T = ray.m_origin;
		T -= v0;
	}
	else
	{
		T = v0;
		T -= ray.m_origin;
		det = -det;
	}

	// If determinant is near zero, ray lies in plane of triangle
	if (det < Math::epsilon)
	{
		return false;
	}

	// Calculate u and make sure u <= 1
	u = T.dot(P);
	if (u < 0.0f || u > det)
	{
		return false;
	}

	// Q
	Vector3 Q(T);
	Q.cross(E1);

	// Calculate v and make sure u + v <= 1
	v = ray.m_direction.dot(Q);
	if (v < 0.0f || u + v > det)
	{
		return false;
	}

	// Calculate t, scale parameters, ray intersects triangle
	travel = E2.dot(Q);

	decimal fInvDet = 1.0f / det;
	travel *= fInvDet;
	u *= fInvDet;
	v *= fInvDet;

	return true;
}